
<div class="row">
  <div class="col-xs-6 col-md-8">
    <ul class="ztree" id="treeDemo"></ul>
  </div>
  <div class="col-xs-6 col-md-4">
  </div>
</div>



<link rel="stylesheet" href="/static/addon/ztree/bootstrap-style.css">
<script type="text/javascript" src="/static/addon/ztree/jquery.ztree.core.js"></script>
<script type="text/javascript" src="/static/addon/ztree/jquery.ztree.exedit.js"></script>
<script type="text/javascript">
        var setting = {
            view: {
                addHoverDom: addHoverDom,
                removeHoverDom: removeHoverDom,
                selectedMulti: false,
            },
            check: {
                enable: false
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            edit: {
                enable: true
            },
            callback: {
              beforeRemove: zTreeBeforeRemove
            }
        };
        var zNodes =[
            <?php foreach($categories as $items):?>
                {id:<?php echo $items['id'];?>, pId:<?php echo $items['parent_id'];?>, name:"<?php echo $items['name'];?>", open:<?php echo $items['parent_id']==0?'true':'false';?>},
            <?php endforeach;?>
        ];

        $(document).ready(function(){
            $.fn.zTree.init($("#treeDemo"), setting, zNodes);
        });

        var newCount = 1;
        function addHoverDom(treeId, treeNode) {
            var sObj = $("#" + treeNode.tId + "_span");
            if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
            var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
                + "' title='增加分类' onfocus='this.blur();'></span>";
            sObj.after(addStr);
            var btn = $("#addBtn_"+treeNode.tId);
            if (btn) btn.bind("click", function(){
                var newNode = {pId:treeNode.id, name:"新建分类"+(newCount++)}
                $.post("<?php echo site_url('admin/categories/add');?>",newNode,function(result){
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                    zTree.addNodes(treeNode, {id:(100 + newCount), pId:treeNode.id, name:"新建分类" + (newCount++)});
                });
            });
        };
        function removeHoverDom(treeId, treeNode) {
            $("#addBtn_"+treeNode.tId).unbind().remove();
        };

        function zTreeBeforeRemove(treeId, treeNode){
          if(treeNode.pId==0){
              alert('一级分类无法删除');
              return;
          }
          $.post("<?php echo site_url('admin/categories/delete');?>",{id:treeNode.id});
        }
        

    </SCRIPT>

